package com.generalbackend.config;

import lombok.extern.slf4j.Slf4j;
import org.flywaydb.core.Flyway;
import org.flywaydb.core.api.FlywayException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;

/**
 * @author tim.xie
 * @date 2021/12/13 10:25
 */
@Slf4j
@Component
public class FlywayConfig {

    @Autowired
    private DataSource dataSource;

    @Value("${spring.flyway.baseline-on-migrate}")
    private boolean baselineOnMigrate;

    @Value("${spring.flyway.validate-on-migrate}")
    private boolean validateOnMigrate;

    @PostConstruct
    public void migrate() {
        Flyway flyway = new Flyway();

        flyway.setDataSource(dataSource);
        flyway.setLocations("db/migration");
        flyway.setEncoding("UTF-8");

        flyway.setBaselineOnMigrate(baselineOnMigrate);
        flyway.setValidateOnMigrate(validateOnMigrate);

        try {
            flyway.migrate();
        }catch (FlywayException e) {
            log.error("Flyway配置加载出错");
        }
    }

}
